package other;

import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class HorseChessboard {
    private static int rowNum=8;
    private static int columnNum=8;
    private static boolean isVisited[][]=new boolean[rowNum][columnNum];
    private static boolean isFinished = false;
    public static void main(String[] args) {
        int board[][] = new int[rowNum][columnNum];
        exec(board,3,2,1);
        for(int[] a:board){
            System.out.println(Arrays.toString(a));
        }
        System.out.println(isFinished);
    }
    public static void exec(int board[][],int row,int column,int step){
        //假设当前点可以走
        board[row][column] = step;
        isVisited[row][column]=true;
        ArrayList<Point> list = getNextPoints(row,column);
        list.sort(new Comparator<Point>() {
            @Override
            public int compare(Point o1, Point o2) {
                int size1 = getNextPoints(o1.y,o1.x).size();
                int size2 = getNextPoints(o2.y,o2.x).size();
                return size1-size2;
            }
        });
        while(!list.isEmpty()){
            Point p = list.remove(0);
            if(!isVisited[p.y][p.x]){
                exec(board,p.y,p.x,step+1);
            }
        }
        if(step<rowNum*columnNum&&!isFinished){
            board[row][column] = 0;
            isVisited[row][column] = false;
        }else {
            isFinished = true;
        }
    }

    public static ArrayList<Point> getNextPoints(int row,int column){
        ArrayList<Point> list = new ArrayList<>();
        Point p = new Point();
        if((p.x=column-2)>=0&&(p.y=row+1)<rowNum){
            list.add(new Point(p));
        }
        if((p.x=column-2)>=0&&(p.y=row-1)>=0){
            list.add(new Point(p));
        }
        if((p.x=column+2)<columnNum&&(p.y=row+1)<rowNum){
            list.add(new Point(p));
        }
        if((p.x=column+2)<columnNum&&(p.y=row-1)>=0){
            list.add(new Point(p));
        }
        if((p.x=column-1)>=0&&(p.y=row+2)<rowNum){
            list.add(new Point(p));
        }
        if((p.x=column-1)>=0&&(p.y=row-2)>=0){
            list.add(new Point(p));
        }
        if((p.x=column+1)<columnNum&&(p.y=row+2)<rowNum){
            list.add(new Point(p));
        }
        if((p.x=column+1)<columnNum&&(p.y=row-2)>=0){
            list.add(new Point(p));
        }
        return list;
    }
}
